package br.inf.solutions.apresentacoes.ssp.control.validator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import br.com.vexillum.control.manager.ExceptionManager;
import br.com.vexillum.control.validator.Validator;
import br.com.vexillum.util.ReflectionUtils;
import br.com.vexillum.util.Return;
import br.com.vexillum.util.SpringFactory;
import br.inf.solutions.apresentacoes.ssp.control.NeighborhoodController;
import br.inf.solutions.apresentacoes.ssp.model.Neighborhood;

public class NeighborhoodValidator extends Validator{

	public NeighborhoodValidator(Map<String, Object> mapData) {
		super(mapData);		
	}
	
	@Override
	public Return validateSave(){
		Return ret = super.validateSave();
		if(ret.isValid())
			ret.concat(existsName());		
		return ret;
	}
	
	public Return validateSearchByCriteria(){
		Neighborhood bairro = (Neighborhood) entity;
		Return ret = creatReturn(null, getValidationMessage(null, "searchbycriteria", false));
		try {
			for (Field field : ReflectionUtils.getSearchFields(bairro)) {
				field.setAccessible(true);
				if(!field.getName().equals("ativo") && field.get(bairro) != null && !field.get(bairro).toString().equals("")){
					return new Return(true);
				}
			}
		} catch (Exception e) {
			ret = new ExceptionManager(e).treatException();
		}
		return ret;
	}
	
	private Return existsName(){
		Return ret = new Return(true);
		Neighborhood bar = (Neighborhood) entity;
		HashMap<String, Object> data = new HashMap<String, Object>();
				
		data.put("sql", "FROM Neighborhood WHERE name = '" + bar.getName() + "' AND city = '" + bar.getCity().getId() + "'");
		
		NeighborhoodController controlador = SpringFactory.getController("neighborhoodController", NeighborhoodController.class, data);
		if(!controlador.searchByHQL().getList().isEmpty()){
			ret.concat(creatReturn("name", getValidationMessage("name", "exists", true)));
		}
		return ret;
	}
}